package com.mrx.giteewebhook.service;

import com.alibaba.fastjson2.JSON;
import com.mrx.giteewebhook.model.request.push.PushRequest;
import com.mrx.giteewebhook.utils.GiteeSignUtil;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author Mr.X
 * @since 2024-03-08 下午 8:46:39
 */
@Service
public class GiteeWebhookService {

    private static final String secret = System.getenv("GITEE_SECRET");

    private static final Logger logger = LoggerFactory.getLogger(GiteeWebhookService.class);

    @PostConstruct
    public void init() {
        Assert.hasText(secret, "密钥不能为空, 是否忘记设置环境变量 GITEE_SECRET 了?");
    }

    public Object onPush(PushRequest pushRequest, String sign, Long timestamp) {
        Assert.isTrue(sign.equals(GiteeSignUtil.calcSignature(secret, timestamp)), "Invalid signature");
        logger.info("触发 push WebHook: {}", JSON.toJSONString(pushRequest));
        return "succeed";
    }

}
